<?php

    /**
    * This is the model class for table "post".
    *
    * The followings are the available columns in table 'post':
    * @property string $id
    * @property string $cat_id
    * @property string $title
    * @property string $title_en
    * @property string $alias
    * @property string $alias_en
    * @property string $content
    * @property string $content_en
    * @property string $desc
    * @property string $desc_en
    * @property string $image
    * @property string $created
    * @property string $changed
    * @property string $view
    * @property string $manager_id
    * @property string $status
    * @property string $type
    * @property string $post_fb
    *
    * The followings are the available model relations:
    * @property Comment[] $comments
    * @property Manager $manager
    * @property Cat $cat
    */
    class Post extends Model
    {
        public $title_other = '';
        public $upload_method = 'file';
        public $image_file;
        public $image_url;

        public $post_fb = 0;
        /**
        * Returns the static model of the specified AR class.
        * @param string $className active record class name.
        * @return Post the static model class
        */
        public static function model($className=__CLASS__)
        {
            return parent::model($className);
        }

        /**
        * @return string the associated database table name
        */
        public function tableName()
        {
            return 'post';
        }

        /**
        * @return array validation rules for model attributes.
        */
        public function rules()
        {
            // NOTE: you should only define rules for those attributes that
            // will receive user inputs.
            return array(

                array('cat_id, title, desc, manager_id', 'required'),

                array('cat_id', 'length', 'max'=>10),
                array('title, title_en, alias, alias_en, image, status, type, has_en, post_fb, image_url, created, changed', 'length', 'max'=>255),
                array('desc, desc_en, ', 'length', 'max'=>500),

                array('image_file', 'file', 'allowEmpty' => true, 'on' => 'create', 'message'=>'Chọn 1 ảnh để upload'),
                array('image_file', 'file', 'types'=>'png, jpg, jpeg, gif', 'allowEmpty' => true, 'message'=>'Định dạng phải là: png, jpg, jpeg, gif'),

                array('upload_method', 'checkUpload', 'on' => 'create'),

                array('content_en, content', 'safe'),

                // The following rule is used by search().
                // Please remove those attributes that should not be searched.
                array('id, cat_id, title, title_en, alias, alias_en, content, content_en, desc, desc_en, keyword, keyword_en', 'safe', 'on'=>'search'),
            );
        }

        public function checkUpload($attribute, $params)
        {
            //        if(!$this->hasErrors())
            //        {
            $post = $_POST[$this->class];
            $files = $_FILES[$this->class];
            if($post['upload_method'] == 'url' && !$post['image_url']){
                $this->addError('upload_method', 'Bạn cần điền 1 đường dẫn ảnh');
            }elseif($post['upload_method'] == 'file' && !$files['size']['image_file']){
                $this->addError('upload_method', 'Bạn cần chọn 1 ảnh để upload');
            }   
            //        }
        }



        /**
        * @return array relational rules.
        */
        public function relations()
        {
            // NOTE: you may need to adjust the relation name and the related
            // class name for the relations automatically generated below.
            return array(
                'manager' => array(self::BELONGS_TO, 'Manager', 'manager_id'),
                'cat' => array(self::BELONGS_TO, 'PostCat', 'cat_id'),
                'comments' => array(self::HAS_MANY, 'Comment', 'post_id', 'order'=>'created ASC'),
            );
        }

        /**
        * @return array customized attribute labels (name=>label)
        */
        public function attributeLabels()
        {
            return array(
                'id' => 'ID',
                'cat_id' => Yii::t('app', 'Chuyên mục'),
                'title' => Yii::t('app', 'Tiêu đề'),
                'title_en' => Yii::t('app', 'Tiêu đề tiếng anh'),
                'content' => Yii::t('app', 'Nội dung'),
                'content_en' => Yii::t('app', 'Nội dung tiếng anh'),
                'desc' => Yii::t('app', 'Tóm tắt'),
                'desc_en' => Yii::t('app', 'Tóm tắt tiếng anh'),
                'keyword' => Yii::t('app', 'Từ khóa'),
                'keyword_en' => Yii::t('app', 'Từ khóa tiếng anh'),
                'image' => Yii::t('app', 'Ảnh đại diện'),
                'upload_method' => Yii::t('app', 'Phương thức tải ảnh'),
                'has_en' => Yii::t('app', 'Bật phiên bản tiếng anh'),
            );
        }

        public function getUrlID(){
            return Yii::app()->createAbsoluteUrl('/web/post/view', array('id' => $this->id));
        }
        public function getUrl(){
            return Yii::app()->createAbsoluteUrl('/web/post/view', array(
                'cat_alias' => $this->lang == 'en' ? $this->cat->alias_en : $this->cat->alias,
                'id'=>$this->id,
                'alias'=> $this->lang == 'en' ? $this->alias_en : $this->alias,
                'lang'  => $this->lang,
            ));
        }
        public function getAdminUrl($type = 'view') {
            return Yii::app()->createUrl('/admin/post/' . $type, array("id" => $this->id));
        }

        public function getUrlOther(){
            return Yii::app()->createAbsoluteUrl('post/view', array(
                'id'=>$this->id,
                'alias'=> $this->lang == 'en' ? $this->alias : $this->alias_en,
                'lang'  => $this->lang == 'en' ? 'vi' : 'en',
            ));
        }

        /**
        * Detect news by lang
        * 
        * @param string $lang vi or en
        */
        public function detectByLang(){
            if($this->lang == 'en'){
                $this->title_other = $this->title;
                $this->title = $this->title_en;
                $this->desc = $this->desc_en;
                $this->content = $this->content_en;
            }else{
                $this->title_other = $this->title_en;
            }

        }

        public function getIsEditor(){
            $user = Yii::app()->user;
            if($user->id){
                if($user->manager->isAdmin) return TRUE;

                if($user->manager->id == $this->id) return TRUE;
            }
            return FALSE;
        }

        public function getDescShort($limit = 20){
            return TextParser::word_limiter($this->desc, $limit);
        }

        public function getImageUrl($type = 'medium', $getPath = FALSE){ // large, medium, small, square
            $imgConf = Yii::app()->params->post_img;
            if($getPath){
                return $imgConf['path'].$this->id."/{$this->image}_{$type}.jpg"; 
            }
            return Yii::app()->getBaseUrl(true).'/'.$imgConf['path'].$this->id."/{$this->image}_{$type}.jpg";
        }
        public function getImageUrlSmall(){
            return $this->getImageUrl('small');
        }
        public function getImageUrlMedium(){
            return $this->getImageUrl('medium');
        }
        public function getImageUrlLarge(){
            return $this->getImageUrl('large');
        }
        public function getImageUrlSquare(){
            return $this->getImageUrl('square');
        }

        public function getCreatedTime(){
            return $this->getCreatedDate();
            return MyDateTime::relative($this->created);
        }
        public function getCreatedDateNum(){
            return date('m-d-Y', strtotime($this->created));
        }
        public function getCreatedDate(){
            return date('F d, Y', strtotime($this->created));
        }

        public function getTitleEncode(){
            return CHtml::encode($this->title);
        }

        public function getContentShort($words = 50 , $inline = FALSE){
            $content = strip_tags($this->content);
            $content = str_replace('&nbsp;', ' ', $content);
            if($inline) $content = preg_replace('{[\n\s]+}', ' ', $content);
            return Myext::word_limiter(trim($content), $words);
        } 

        private $_newerPost;
        public function getNewerPost(){
            if($this->_newerPost) return $this->_newerPost;
            return $this->_newerPost = $this->with('cat')->find(new CDbCriteria(array(
                'condition' => "t.id > {$this->id} AND t.`status` = 'ENABLE'",
                'order' => 't.id ASC',
            )));
        }

        private $_olderPost;
        public function getOlderPost(){
            if($this->_olderPost) return $this->_olderPost;
            return $this->_olderPost = $this->with('cat')->find(new CDbCriteria(array(
                'condition' => "t.id < {$this->id} AND t.`status` = 'ENABLE'",
                'order' => 't.id DESC',
            )));
        }

        private $_relatedPosts;
        public function getRelatedPosts($limit = 9){
            if($this->_relatedPosts) return $this->_relatedPosts;
            return $this->_relatedPosts = $this->cat->posts(array(
                'condition' => "id <> {$this->id} AND `status` = 'ENABLE'",
                'limit'     => $limit,
            ));
        }


        public function getStatusData(){
            return array(
                'ENABLE' => 'Enable',
                'DISABLE' => 'Disable',
            );
        }

        public function getStatusLabel(){
            return $this->statusData[$this->status];
        }

        public function getTypeData(){
            return array(
                'HOT' => Yii::t('app', 'HOT'),
                'VIP' => Yii::t('app', 'VIP'),
            );
        }
        public function getTypeLabel(){
            return $this->typeData[$this->type];
        }

        public function submitSitemap(){
            $siteMap = Yii::app()->createAbsoluteUrl('/sitemap/index');
            $searchEngines = array(
                "http://www.google.com/webmasters/sitemaps/ping?sitemap={$siteMap}",
                "http://www.bing.com/webmaster/ping.aspx?siteMap={$siteMap}",
            );
            foreach($searchEngines as $s){
                @file_get_contents($s); 
            }
        }

        public function postFacebook(){

            $fbConf = Yii::app()->params->facebook;
            $fbPageId = $fbConf['pageId'];

            Yii::import('ext.facebook.src.Facebook');
            $facebook = new Facebook(array(
                'appId'  => $fbConf['appId'],
                'secret' => $fbConf['secret'],
            ));

            //            # get tokenKey, another action
            //            if(isset($_GET['code'])){
            //                echo '<pre>';print_r($facebook->getAccessToken());echo '</pre>';die;
            //            }
            //            $fbLoginUrl = $facebook->getLoginUrl(array(
            //                'scope' => 'publish_stream,manage_pages',
            //                'redirect_uri' => $this->baseUrl.Yii::app()->request->requestUri,
            //            ));
            //            Yii::app()->controller->redirect($fbLoginUrl);


            $tokenKey = 'CAAGEyT5tQaoBACa8MXL2pC6Y66rO1KdCXZA2VmixkHY0HH22He7ZBQGrm7ZBvLLXR3mx0rRIP8HlXoFDBpu1geYQUGWOZA0QDTcfmb7s8ZBQbLPviOkgIl7wFDDDYOYHxXODk0d2a4BhUXIRwPZBhe52G8JVZBJjmsZD';
            $facebook->setAccessToken($tokenKey);
            $msg_body = array(
                'link' => $this->url,
                'message' => $this->title."\n\n".$this->getContentShort(60) ."\n\nSee details at the link below ↓",
                'picture' => $this->getImageUrlSmall(), 
                'published' => true,
            );
            $postResult = $facebook->api("/{$fbPageId}/links", 'post', $msg_body );
        }

        public function getPost_id(){
            return $this->id;
        }

        public function getCatUrl(){
            return $this->cat->url;
        }
        public function getCatName(){
            return $this->cat->name;
        }
        public function getManagerName(){
            return $this->manager->name;
        }


        public function detectVideo(){
            $contentHasVideo = preg_match('{\[video\]([^\]]+)\[\/video\]}', $this->content);
            if($contentHasVideo){
                $this->content = $this->parseVideo($this->content);
            }
            return $contentHasVideo;
        }

        private function parseVideo($content){
            //[video]http://totalhairregrowth.com/jwplayer/thrvid.flv[/video]
            //<div class="video-player" url="http://totalhairregrowth.com/jwplayer/thrvid.flv">Video Loading ...</div> 
            //            return preg_replace(
            //            '{\[video\ play](.+)\[\/video\]}', 
            //            '<div class="video-player" url="$1">Video Loading ...</div>', 
            //            $content);
            return preg_replace_callback(
                '{\[video(?:\s+(play))?\]([^\]]+)\[\/video\]}', 
                'self::videoReplaceCallback',
                $content
            );  
        }
        private function videoReplaceCallback($matches){
            $autoplay = trim($matches[1]) == "play" ? 'true' : 'false';
            $url = trim($matches[2]);
            return "<div class=\"video-player\" autostart=\"{$autoplay}\" url=\"{$url}\">Video Loading ...</div>";
        } 


}